#!/bin/bash

#更改工作目录
cd `dirname $0`

. ./conf.sh

# 检查环境
check_env()
{
	local username=`whoami`
	if [ "$username" != "root" ]; then
		echo "please run root"
		exit
	fi
	
	return 1;
}

# 获取参数
if [ $# -lt 3 ]; then
    echo "sh $0 ip 抓包时间(sec) 保存数据包名"
    echo "eg."
    echo "  sh $0 \"192.168.1.119\" 30 oracle_0717.pcap"
    exit
fi
var_ip=$1
var_time=$2
var_file_dump=$3

var_filter="(host $var_ip) or (vlan and host $var_ip)"
var_file_dir=`dirname $var_file_dump`

# 检查环境
check_env;

var_date_now=`date +%Y%m%d%H%M%S`
var_file_temp=$VAR_DIR_DUMP"/dump"_${var_date_now}
# 数据抓包
mkdir -p $VAR_DIR_DUMP >/dev/null 2>&1
rm -f var_file_temp >/dev/null 2>&1
echo "tcpdump -i $VAR_DEV \"$var_filter\" -w $var_file_temp"
tcpdump -i $VAR_DEV "$var_filter" -w $var_file_temp &
var_pid_tcpdump=$!

# 等待抓包完成
var_step=1
while ((var_step<=$var_time))
do
    kill -0 $var_pid_tcpdump
    if [ $? -gt 0 ]; then
        echo "tcpdump close"
    fi
    echo "...$var_step"
    let ++var_step
    sleep 1
done

kill $var_pid_tcpdump
sleep 1
echo "kill tcpdump"

mkdir -p $var_file_dir
mv $var_file_temp $var_file_dump
echo "pcap file [$var_file_dump]"

